<template>
  <div class="main">
    <h1>长时间无鼠标操作示例</h1>
    <p>交卷倒计时：{{ timeout }}</p>
    <p>
      <button @click="fn_bind">绑定</button>
      <button @click="fn_unbind">解绑</button>
    </p>
  </div>
</template>

<script>
export default {
  props: {
    pro_timeout: {
      type: Number,
      default: 60 * 2 // 2 分钟
    }
  },
  data() {
    return {
      timeout: this.pro_timeout,
      timer: null,
    };
  },
  mounted() {
    this.fn_bind()
    // 组件挂载后启动定时器
    this.startTimer();
  },
  methods: {
    fn_bind() {
      document.addEventListener('mousemove', this.resetTimer);
      document.addEventListener('mousedown', this.resetTimer);
    },
    fn_unbind() {
      document.removeEventListener('mousemove', this.resetTimer);
      document.removeEventListener('mousedown', this.resetTimer);
    },
    startTimer() {
      this.timeout = this.pro_timeout
      this.timer = setInterval(() => {
        --this.timeout
        if (this.timeout === 10) {
          this.showWarning();
        } else if (this.timeout <= 0) {
          this.handleInactivity();
          clearTimeout(this.timer);
          this.fn_unbind()
        }
      }, 1000);
    },
    resetTimer() {
      // 清除当前定时器
      clearTimeout(this.timer);
      // 重新启动定时器
      this.startTimer();
    },
    showWarning() {
      this.$message.warning('请移动鼠标否则 ' + (this.timeout) + ' 秒后自动交卷');
    },
    handleInactivity() {
      // 长时间无操作时触发的事件，这里模拟自动交卷
      this.$message.error('由于长时间无操作，已自动交卷！');
      // 你可以在这里添加更多的逻辑，比如提交表单等
      this.$emit('handleInactivity');
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器，避免内存泄漏
    clearTimeout(this.timer);
    this.fn_unbind()
  }
};
</script>